package com.ls.controller;

import com.ls.entity.HandSet;
import com.ls.service.HandSetService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class HandSetController {
    @Resource
    private HandSetService handSetService;

    @RequestMapping(value = "/list")
    public String list(Model model) {
        List<HandSet> list = handSetService.getAll();

        if (list != null) {
            model.addAttribute("list", list);
        }

        return "list";
    }

    @RequestMapping(value = "/select/{id}")
    public String getHandSetById(@PathVariable Integer id, Model model) {
        HandSet handSet = handSetService.getHandSetById(id);

        if (handSet != null) {
            model.addAttribute("handSet", handSet);
        }

        return "select";
    }

    @RequestMapping(value = "/del/{id}")
    public void del(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        int ret = handSetService.del(id);

        if (ret > 0) {
            out.print("<script>");
            out.print("alert('删除成功!');");
            out.print("location.replace('http://localhost:8080/HandSetSys/list');");
            out.print("</script>");
            out.flush();
            out.close();
        } else {
            out.print("<script>");
            out.print("alert('删除失败!');");
            out.print("window.history.back();");
            out.print("</script>");
            out.flush();
            out.close();
        }
    }
}